package cn.com.wxd.biz.website;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.entity.website.ArticleInfo;
import cn.com.wxd.entity.website.CatalogInfo;
import cn.com.wxd.common.PageInfo;
import cn.com.wxd.util.action.AccessLogUtil;
import cn.com.wxd.util.framework.LocalCacheUtil;
import cn.com.wxd.util.SpringContextHolder;
import cn.com.wxd.util.website.WebsiteInfo;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

/**
 * Title:WebsiteCache.java
 * Description:cn.com.wxd.biz.website
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2016-5-10 下午5:00:35
 *
 * @author WangXuDong
 * @version 1.0
 */
public class WebsiteCache implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 7322555921931036025L;
    private static final Logger log = LoggerFactory.getLogger(WebsiteCache.class);
    /**
     * 储存所有栏目的缓存
     */
    private static List<CatalogInfo> catalog;
    /**
     * 存储文章的空间 key为caid value为文章列表
     */
    private static Cache websiteCache;
    /**
     * 不提供销毁或清空缓存方法的缓存，该缓存不会因为其他缓存的清理而清空
     */
    private static Cache noRefreshCache;
    /**
     * 网站对象缓存，此缓存在其他缓存刷新后被自动清空
     * key名称 value值
     */
    private static Cache websiteObjectCache;
    private static LocalCacheUtil util;
    private static CatalogService catalogService;
    private static ArticleService articleService;

    public static void init() {
        //从spring持有类中获取注入的对象
        catalogService = SpringContextHolder.getBean("catalogService", CatalogServiceImpl.class);
        articleService = SpringContextHolder.getBean("articleService", ArticleServiceImpl.class);
        util = LocalCacheUtil.getInstance();
        noRefreshCache = util.getCache("noRefreshCache");
        if (noRefreshCache == null) {
            util.addCache("noRefreshCache");
            noRefreshCache = util.getCache("noRefreshCache");
        }
        util.addCache("websiteCache");
        websiteCache = util.getCache("websiteCache");
        util.addCache("websiteObjectCache");
        websiteObjectCache = util.getCache("websiteObjectCache");
        refreshAllCache();
    }

    private WebsiteCache() {
        try {
            throw new Exception("无法实例化对象WebsiteCache");
        } catch (Exception e) {
            log.error("", e);
        }
    }

    /**
     * 获取所有栏目
     *
     * @return
     */
    public static List<CatalogInfo> getCatalog() {
        if (catalog == null || catalog.size() == 0) {
            catalog = getCatalogService().getAllCatalogFormDb(null);
        }
        return catalog;
    }

    /**
     * 刷新某个栏目下文章的缓存
     *
     * @param caid
     */
    public static void refreshCache(int caid) {
        if (caid >= 0) {
            //查询出了相关的文章列表
            int maxcount = WebsiteInfo.getCacheMaxCount();
            if (maxcount <= 0) {
                log.warn("网站缓存数量配置有误!现在默认为20");
                maxcount = 20;
            }
            List<ArticleInfo> liart = getArticleService().getArticlesFromDb(String.valueOf(caid), new PageInfo(1,
                    maxcount));
            if (liart != null) {
                if (websiteCache.get(caid) != null) {
                    websiteCache.remove(caid);
                }
                websiteCache.put(new Element(caid, liart));
            }
            //清空方法缓存
            util.removeAll("websiteObjectCache");
        }
    }

    /**
     * 刷新栏目缓存
     */
    public static void refreshCatalogCache() {
        catalog = getCatalogService().getAllCatalogFormDb(null);
        websiteObjectCache.removeAll();  //清空方法缓存
    }

    /**
     * 刷新网站的所有缓存,谨慎使用此方法(等待时间过长)
     */
    @Deprecated
    public static void refreshAllCache() {
        catalog = getCatalog();
        if (catalog != null) {
            for (int i = 0; i < catalog.size(); i++) {
                refreshCache(catalog.get(i).getId());
            }
        } else {
            log.info("无法刷新缓存，网站中没有数据!");
        }
        websiteObjectCache.removeAll();  //清空方法缓存
    }

    /**
     * 获取网站的缓存
     *
     * @return Map Key栏目号     value文章列表
     */
    public static Map<Integer, List<ArticleInfo>> getWebsiteCache() {
        if (websiteCache == null) {
            refreshAllCache();
        }
        Map<Integer, List<ArticleInfo>> map = new HashMap<>();
        for (Object key : websiteCache.getKeys()) {
            map.put((Integer) key, (List<ArticleInfo>) (websiteCache.get(key).getObjectValue()));
        }
        return map;
    }

    /**
     * 获取在线人数
     *
     * @return
     */
    public static int getOnlineUser() {
        return AccessLogUtil.getOnlineUser();
    }

    /**
     * 获取总访问量
     *
     * @return
     */
    public static int getTatorAccessVolume() {
        return AccessLogUtil.getTatorAccessVolume();
    }

    private static CatalogService getCatalogService() {
        if (catalogService == null) {
            init();
        }
        return catalogService;
    }

    private static ArticleService getArticleService() {
        if (articleService == null) {
            init();
        }
        return articleService;
    }

    /**
     * 网站对象缓存
     * key名称 value值
     */
    public static Object getWebsiteObjectCache(String key) {
        if (websiteObjectCache == null) {
            refreshAllCache();
        }
        Element ele = websiteObjectCache.get(key);
        if (ele != null) {
            return ele.getObjectValue();
        }
        return null;
    }

    /**
     * 网站对象缓存
     * key名称 value值
     */
    public static void setWebsiteObjectCache(String key, Object value) {
        if (websiteObjectCache == null) {
            refreshAllCache();
        }
        if (websiteObjectCache.get(key) != null) {
            websiteObjectCache.remove(key);
        }
        websiteObjectCache.put(new Element(key, value));
    }

    /**
     * 网站对象缓存
     * key名称 value值
     */
    public static void removeWebsiteObjectCache(String key) {
        if (websiteObjectCache == null) {
            refreshAllCache();
        }
        websiteObjectCache.remove(key);
    }

    /**
     * 获取永远不被清理的缓存缓存
     *
     * @param name
     *
     * @return
     */
    public static Object getNoRefreshCache(String name) {
        Element ele = noRefreshCache.get(name);
        if (ele != null) {
            return ele.getObjectValue();
        }
        return null;
    }

    /**
     * 设置永远不被清理的缓存
     *
     * @param name
     * @param value
     */
    public static void setNoRefreshCache(String name, Object value) {
        if (noRefreshCache.get(name) != null) {
            noRefreshCache.remove(name);
        }
        noRefreshCache.put(new Element(name, value));
    }

    /**
     * 手动删除缓存中的某个数据
     *
     * @param name
     */
    public static void removeNoRefreshCache(String name) {
        noRefreshCache.remove(name);
    }
}
